# -*- coding: utf-8 -*-

import socket

from tornado.tcpserver import TCPServer
from business_top.poll_file_send_ssh import poll_file_send_ssh
from program_top.utilities.decorators import load_class_config

@load_class_config
class tcp_tunnel_via_file(TCPServer, poll_file_send_ssh):
	
	def __init__(self):
		super(tcp_tunnel_via_file, self).__init__()
		self.__initialise()
		pass
	
	def __notice_start(self):
		self.__write_fp.write("started")
		self.__write_fp.flush()
		pass
	
	def intry(self, data):
		
		pass
	'''
	def start(self):
		
		
		while 1:
			
			self.__listening_socket.listen(self.config['max_connection_count'])
			(current_socket_connection, coming_address)=self.__listening_socket.accept()
			self.__connection_dict[coming_address]=read_socket_write_file(fd=current_socket_connection, address=coming_address, buffer_size=self.config['buffer_byte'],
			                                                              buffer_filename=self.__write_buffer_file)
			
			pass
		
		pass
	'''
	
	def __initialise(self):
		self.__connection_dict={}#所有连接放进这个字典
		self.__create_buffer_files_if_empty()
		self.__make_fp()
		self.__live=True
		self.__check_file()
		
		#self.listen(self.config['local_listen_port'])
		
		#self.__start_listen()
		pass
		
	def __write_chunk_to_file(self,one_trunk):
		print(one_trunk)
		
		pass
	
	def handle_stream(self, stream, address):
		if not self.__connection_dict.__contains__(address):#记录连接
			self.__connection_dict[address]=stream
			stream.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
			self.__write_fp.write(b'start')
			self.__write_fp.flush()
		
		stream.read_bytes(num_bytes=self.config['buffer_byte'], callback=self.__write_chunk_to_file, streaming_callback=None,
               partial=False)
		
		
		pass
	
	def __make_fp(self):
		'''创建缓存文件的描述符'''
		self.__read_fp=open(self.__read_buffer_file,mode='wb+')
		self.__write_fp=open(self.__write_buffer_file,mode='wb+')
	
	def __create_buffer_files_if_empty(self):
		'''双工使用，读写分离'''
		
		write_from_out="write_from_out.txt"
		write_from_in="write_from_in.txt"
		
		#外侧文件从外缓存写，否则从内缓存写
		my_write_buffer_name=write_from_out if self.config['outside'] else write_from_in
		my_read_buffer_name=write_from_in if self.config['outside'] else write_from_out
		
		self.__write_buffer_file=self.config['local_buffer_path']+my_write_buffer_name
		self.__read_buffer_file=self.config['local_buffer_path']+my_read_buffer_name
		
		pass
	
	def __socket_builder(self):
		current_socket=socket(AF_INET, SOCK_STREAM)
		current_socket.bind(("127.0.0.1", self.config['local_listen_port']))
	
	def __start_listen(self):
		
		pass
	pass